<template>
  <div>
    <basic-dialog
      :visible="visible"
      min-width="864px"
      :isShowClose="false"
      is-show-basic-footer
      @close="handleClose"
      @submit="handleOk"
      title="添加设备">
      <q-form
        greedy
        class="dialog-content block">
        <yz-condition-filter
          v-model="queryParams"
          @resetSearch="resetSearch"
          @onSubmit="onSubmit"
          class="padding-t-20"
        >
          <select-tooltip
            v-model="queryParams.deviceType"
            isShowAll
            :multiple="false"
            :options="deviceTypeOption"
            msg="设备类型"
          ></select-tooltip>
          <q-select
            class="margin-r-20"
            v-model="queryParams.processingEquipment"
            outlined
            hide-selected
            use-input
            fill-input
            input-debounce="500"
            :options="processingEquipmentOption"
            @filter="filterFn"
            @popup-hide="popUpHide"
            placeholder="设备名称/编号"
            dense
            type="text"
            clearable
            options-dense
            emit-value
            map-options
            :rules="[]"
          >
            <template v-slot:option="scope">
              <q-item
                v-bind="scope.itemProps"
                v-on="scope.itemEvents"
              >
                <q-item-section>
                  <q-item-label v-html="scope.opt.label" />
                </q-item-section>
                <q-item-section side>
                  <q-item-label v-html="scope.opt.assetNumber" />
                </q-item-section>
              </q-item>
            </template>
            <template v-slot:before>
              <label class="text-right name label-width" style="position: relative">
                <span>加工设备:</span>
              </label>
            </template>
          </q-select>
        </yz-condition-filter>
        <q-table
          selection="single"
          :selected.sync="selected"
          :data="tableDataFilter"
          :columns="columns"
          row-key="id"
          class="myTable scroll scrollbar inherit"
          :loading="isTableLoading"
          :hide-bottom="tableDataFilter.length !== 0"
          :pagination.sync="pagination"
          color="primary"
          style="max-height: 400px"
        >
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-radio dense v-model="selected[0]" :val="props.row.id" />
              </q-td>
              <q-td>
                {{ props.row.assetNumber || '--' }}
              </q-td>
              <q-td>
                {{ props.row.name || '--'}}
              </q-td>
              <q-td>
                {{ props.row.deviceTypeName || '--' }}
              </q-td>
              <q-td>
                {{ props.row.model || '--' }}
              </q-td>
              <q-td>
                {{ props.row.deviceSpec || '--' }}
              </q-td>
            </q-tr>
          </template>
        </q-table>
        <div style="width: 100%;padding-top: 20px">
          <pagination
            style="position: relative;padding: 0 20px"
            v-model="pagination.page"
            :page-size="pagination.rowsPerPage"
            :total="totalFilter"
            @changePage="onPageChange"
            @changePageSize="onPageSizeChange">
          </pagination>
        </div>
      </q-form>
    </basic-dialog>
  </div>
</template>

<script>
import { getDisLineDevice } from '../../../../boot/system/fixed-scheduling'
import { getDict } from '../../../../boot/common/dict'
import Pagination from 'src/components/pagination'

export default {
  name: 'AddOrEditEquipmentDialog',
  components: {
    Pagination
  },
  props: {
    workshop: {
      type: [Number, String],
      default: ''
    },
    selDevice: {
      type: Array,
      default: () => []
    },
    delDeviceIds: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      fuzzyFunc: getDisLineDevice,
      queryParams: {
        deviceType: 'all',
        processingEquipment: ''
      },
      deviceTypeOption: [],
      processingEquipmentOption: [],
      visible: false,
      isTableLoading: false,
      tableData: [],
      selected: [],
      columns: [
        { name: 'assetNumber', label: '设备编号', align: 'left', field: 'assetNumber' },
        { name: 'name', label: '设备名称', align: 'left', field: 'name' },
        { name: 'deviceTypeName', label: '设备类型', align: 'left', field: 'deviceTypeName' },
        { name: 'model', label: '设备型号', align: 'left', field: 'model' },
        { name: 'deviceSpec', label: '设备规格', align: 'left', field: 'deviceSpec' }
      ],
      pagination: {
        page: 1, // 当前页码
        rowsPerPage: 15, // 每页条数
        rowsNumber: 0 // 总条数
      }
    }
  },
  watch: {
    tableDataFilter () {
      this.selected = this.tableDataFilter.length > 0 ? [this.tableDataFilter[0].id] : []
    }
  },
  mounted () {
    getDict('machine_type', false).then(res => {
      this.deviceTypeOption = res.data
    })
  },
  computed: {
    tableDataFilter () {
      if (this.selDevice.length === 0) {
        return this.tableData
      }
      return this.tableData.filter(item => {
        return this.selDevice.findIndex(sel => sel.deviceId === item.id) === -1
      })
    },
    totalFilter () {
      if (this.selDevice.length === 0) {
        return this.pagination.rowsNumber
      }
      let count = 0
      this.tableData.forEach(item => {
        if (this.selDevice.findIndex(sel => sel.deviceId === item.id) > -1) count++
      })
      return this.pagination.rowsNumber - count
    }
  },
  methods: {
    showDialog () {
      this.visible = true
      Object.assign(this.queryParams, this.$options.data().queryParams)
      this.getTable()
    },
    handleClose () {
      this.visible = false
    },
    // 设备模糊搜索
    filterFn (val, update, abort) {
      const params = {
        workshopId: this.workshop,
        pageSize: 100000,
        pageNum: 1,
        deviceTypeCodes: '',
        keyWord: val,
        delDeiceIds: this.delDeviceIds.length === 0 ? '' : this.delDeviceIds
      }
      getDisLineDevice(params).then(res => {
        update(() => {
          const deviceDetail = {}
          res.records.forEach(item => {
            deviceDetail[item.id] = {
              ...item
            }
            item.value = item.id
            item.label = item.name
          })
          this.processingEquipmentOption = res.records
        })
      }).finally(() => {
        const filterList = this.processingEquipmentOption.filter(val => val.value === this.queryParams.processingEquipment)
        if (!filterList.length && val) {
          this.queryParams.processingEquipment = null
        }
      })
    },
    popUpHide () {
      const filterList = this.processingEquipmentOption.filter(val => val.value === this.queryParams.processingEquipment)
      if (!filterList.length) {
        this.queryParams.processingEquipment = null
      }
    },
    getTable () {
      this.tableData = []
      const deviceName = this.processingEquipmentOption.find(item => item.value === this.queryParams.processingEquipment)
      const params = {
        workshopId: this.workshop,
        pageSize: this.pagination.rowsPerPage,
        pageNum: this.pagination.page,
        deviceTypeCodes: this.queryParams.deviceType === 'all' ? '' : this.queryParams.deviceType,
        keyWord: deviceName ? deviceName.label : '',
        delDeiceIds: this.delDeviceIds.length === 0 ? '' : this.delDeviceIds
      }
      this.isTableLoading = true
      getDisLineDevice(params).then(res => {
        this.tableData = res.records
        this.pagination.rowsNumber = res.total
      }).finally(() => {
        this.isTableLoading = false
      })
    },
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.getTable()
    },
    onPageChange: function (val) {
      this.pagination.page = val
      this.getTable()
    },
    handleOk () {
      const selectId = this.selected[0]
      const selectRow = this.tableData.find(item => item.id === selectId)
      this.visible = false
      this.$emit('success', selectRow)
    },
    onSubmit () {
      this.getTable()
    },
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data().queryParams)
    }
  }
}
</script>

<style scoped lang="stylus">
</style>
